package com.yf.catcafe.controller;

import com.yf.catcafe.pojo.dto.BookingDto;
import com.yf.catcafe.pojo.dto.SeckillCatDto;
import com.yf.catcafe.pojo.enity.Booking;
import com.yf.catcafe.pojo.vo.BookingQueryVo;
import com.yf.catcafe.result.Result;
import com.yf.catcafe.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/catcafe")
@CrossOrigin("*")
public class BookingController {

    @Autowired
    private BooksService booksService;


    @PostMapping("/bookings")
    public Result book(@RequestBody BookingDto bookingDto) {
        String dateStr = bookingDto.getDate(); // 假设你在 DTO 中新增了 date 字段
        String timeSlot = bookingDto.getTimeSlot(); // 新增字段

        // 解析时间区间（取开始时间）
        String[] times = timeSlot.split("-");
        String startTimeStr = times[0]; // 如 "14:00"

        // 拼接完整的时间字符串
        String fullTimeStr = dateStr + "T" + startTimeStr;

        // 解析为 LocalDateTime
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
        LocalDateTime bookingTime = LocalDateTime.parse(fullTimeStr, formatter);

        // 设置到 DTO 中
        bookingDto.setBookingTime(bookingTime);

        booksService.book(bookingDto);
        return Result.success();
    }

    @GetMapping("/bookings/query")
    public Result<List<BookingQueryVo>> queryBookings(){
        List<Booking> bookings=booksService.query();
        List<BookingQueryVo> bookingQueryVo=bookings.stream().map(booking -> {
            BookingQueryVo vo=new BookingQueryVo();
            vo.setNote(booking.getRemark());
            vo.setCatName(booking.getCatName());
            vo.setUserName(booking.getUserNickname());
            vo.setNote(booking.getRemark());
            vo.setId(booking.getId());
            vo.setBookingDate(booking.getBookingTime().toString());
            vo.setOrderDate(booking.getObookingTime().toString());
            return vo;
        }).collect(Collectors.toList());
        return Result.success(bookingQueryVo);
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id){
        booksService.delete(id);
        return Result.success("删除预约信息成功");
    }

    @PostMapping("/bookingsseckill")
    public Result seckillInsert(@RequestBody SeckillCatDto seckillCatDto){
        booksService.seckillInsert(seckillCatDto);
        return Result.success();
    }

}
